class PaymentsController < ApplicationController
  skip_before_filter :verify_authenticity_token

  include ActiveMerchant::Billing::Integrations
  before_filter :login_required,:except => [:alipay_ipn]
  before_filter :find_user,:except => [:alipay_ipn]

  def new
    @order = Order.find(params[:id])
  end

  def alipay_ipn
    notify = Alipay::Notification.new(request.raw_post)

    order = Order.find(notify.order_id)

    if notify.acknowledge
#      begin

        if notify.complete? and order.total_price.to_s == notify.amount and order.status != 5
          order.set_status_complete
        else
#          logger.error("status#{order.total_price}==#{notify.amount}")
#          logger.error("Failed to verify Alipay's notification, please investigate#{order.total_price}==#{notify.amount}")
        end

        if notify.wait_seller_send_goods? and order.total_price.to_s == notify.amount and order.status != 2
          order.set_status_paid
        else
#          logger.error("Failed to verify Alipay's notification, please investigate#{order.total_price}==#{notify.amount}")
        end

#      rescue => e
#        order.status = 9
#        raise
#      ensure
        order.save
#      end
    end

    render :nothing
  end
end
